import axios from 'axios'
import { getToken, removeUserInfo } from './index'
import { ElMessage } from 'element-plus'
import router from '@/router/index'
const request = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 8000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    Authorization: getToken()
}
})
// axios.defaults.headers['content-type'] = 'application/x-www-form-urlencoded'

// 添加请求拦截器
request.interceptors.request.use(
  function (config) {
    if (getToken()) {
      config.headers.Authorization = getToken()
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 添加响应拦截器
request.interceptors.response.use(
  function (res) {
    switch (res.data.code) {
      case 401:
        ElMessage({
          type: 'error',
          message: '用户登录状态过期',
          duration: 2000,
          onClose: () => {
            removeUserInfo()
            router.replace('/login')
          }
        })
        break
      case 403:
        ElMessage({
          type: 'error',
          message: '用户未登录',
          duration: 2000,
          onClose: () => {
            router.replace('/login')
          }
        })
        break

      default:
        break
    }
    return res
  },
  function (error) {
    return Promise.reject(error)
  }
)

export default request
